package com.oedtech.esl.service.nettyService;

import com.oedtech.esl.controller.WebSocketTest;
import com.oedtech.esl.model.esl.Ap;
import com.oedtech.esl.repository.sys.StoreDao;
import com.oedtech.esl.service.eslService.ApService;
import com.oedtech.esl.socket.BsChannelMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证连接合法性
 */
@Component
@ChannelHandler.Sharable
public class AuthHandler extends ChannelInboundHandlerAdapter {
    static Map<String, Channel> map = BsChannelMap.getInstance();
    private final static Logger LOGGER= LoggerFactory.getLogger(AuthHandler.class);
    @Autowired
    private DataService dataService;
    @Autowired
    private StoreDao    storeDao;
    @Autowired
    private ApService apService;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        try {

            byte head = buf.readByte();
            if (head != 0x1b) {
                ctx.close();
                return;
            }
            byte length = buf.readByte();
            byte[] data = new byte[length];
            buf.readBytes(data);
            if ((data[0] & 0xff) != 'p' || (data[7] & 0xff) != '3') {
                ctx.close();
                return;
            }
            String apid = (data[8] & 0xff) + ((data[9] & 0xff) << 8) + "";
            synchronized (map){
                if (map.get(apid)!=null) {
                    ctx.close();
                    return;
                }
                map.put(apid, ctx.channel());
                ;
                apService.saveAp(apid,ctx.channel(),data);
                LOGGER.info("new ap connected, apid:[{}],channel:[{}]",apid,ctx.channel());
                WebSocketTest.sendAll("apConnected",null,apid);
            }

            dataService.ws(ctx.channel(), 0);
            ctx.pipeline().remove(ReadTimeoutHandler.class);
            ctx.pipeline().remove(this);
              //验证通过，移除首次连接的超时handler
            ctx.pipeline().addFirst(new ReadTimeoutHandler(90));  //重新设置正常超时handler
        }finally {
            buf.release();
        }

    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();

        LOGGER.error("AuthHandler--exception",cause);
    }





}
